<template>
  <view class="game theme-2d">
    <!-- 游戏切换 90rpx -->
    <nav-back>
      <view class="navBar">
        <scroll-view class="scrollView" scroll-x scroll-with-animation>
          <view class="gameNav">
            <view class="gameNavItem" :class="index === currentGame ? 'gameNavItemActive' : ''" v-for="(item, index) in games" :key="index" @tap="tabSelect(index)">
              <text class="gameNavItemText">{{ item.name }}</text>
            </view>
          </view>
        </scroll-view>
        <navigator url="/pages/shop/index" class="navigator">积分商城</navigator>
      </view>
    </nav-back>

    <!-- header 430rpx -->
    <view
      class="header bg-gradual-red"
      :style="{
        'background-image': 'url(' + IMAGES.GAME_HEADER_BG + ')'
      }"
    >
      <view class="waiting" v-if="STATE.guessHero.type === 'waiting'"><view>数据正在准备中,请稍等...</view></view>
      <view class="timeing" v-if="STATE.guessHero.type === 'timeing'">
        <view class="logo"><image :src="IMAGES.LOGO_01" mode="widthFix"></image></view>
        <view class="menu" v-if="games && games[currentGame]">
          <navigator :url="'/pages/game/historyAward?game=' + games[currentGame].game" class="cu-btn bg-blue">开奖记录</navigator>
          <navigator :url="'/pages/game/heros?game=' + games[currentGame].game" class="cu-btn bg-blue">英雄资料</navigator>
        </view>
        <view class="countText">
          <view class="text">本游戏中已获得积分:</view>
          <view class="number">{{ STATE.guessHero.scoreTotal | float2int }}</view>
        </view>
        <view class="timer" v-if="STATE.guessHero.type === 'timeing'">
          距离开奖还剩
          <text v-if="time != null" :class="{ animation: time >= 0 && STATE.guessHero.type === 'timeing' }" v-text="time"></text>
          秒
        </view>
        <pre-result v-if="STATE.guessHero.preLotteryResault" class="historyResultBox" :info="STATE.guessHero.preLotteryResault" />
      </view>

      <lottery-animation v-if="STATE.guessHero.type === 'lotterying' || STATE.guessHero.type === 'lotteryed'"></lottery-animation>
    </view>
    <!--  阳光值 60rpx -->
    <spirit></spirit>

    <!-- 预测选项 -->
    <scroll-view class="betting" scroll-y>
      <betting @event-change="onChangeBetting" 
      :win="STATE.guessHero.lotteryResault"></betting>
    </scroll-view>

    
    <!-- 操作面板 80rpx + 30rpx -->
    <view class="settlement">
      <!-- 我的积分 30rpx-->
      <view class="myScore">
        <text class="myScoreLabel">我的积分:</text>
        <text class="myScoreText" v-text="STATE.user.userInfo.score"></text>
      </view>
      
      <view class="settlement-waiting" v-if="STATE.guessHero.type === 'waiting'">数据准备中</view>
      <view class="settlement-timeing" v-else>
        <!-- 预期获得积分 -->
        <view class="operation">
          <view class="operationLeft">
            <view class="expectGetScore">
              <text class="expectGetScoreLabel">预期获得积分:</text>
              <text class="expectGetScoreText">{{ currentScore }}</text>
            </view>
            <view class="consumeSun">
              <text class="consumeSunLabel">消耗阳光值:</text>
              <text class="consumeSunText">{{ currentSun }}</text>
            </view>
          </view>
          <view class="btn active" v-if="STATE.guessHero.type === 'timeing' && !games[currentGame].isSubmit && currentSun > 0" @click="onClickGuess">
            预测
            <text>({{ time }}s)</text>
          </view>
          <view class="btn disabled" v-else>
            预测
            <text v-if="time">({{ time }}s)</text>
            <text v-else>(开奖中)</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { IMAGES } from "@/config/resources";
import navBack from "@/components/navBack";

import lotteryAnimation from "./components/lotteryAnimation";
import Spirit from "./components/spirit";
import betting from "./components/betting";
import preResult from "./components/preResult";
import uniApp from "@/utils/uni-app";
let timer;
import { debounce } from "@/utils";
export default {
  data() {
    return {
      betting: {},

      currentScore: 0, // 当前预期积分
      currentSun: 0, // 当前消耗阳光值

      time: null
    };
  },
  components: {
    navBack,
    lotteryAnimation,
    Spirit,
    betting,
    preResult
  },
  computed: {
    IMAGES: () => IMAGES,
    // 游戏列表
    games() {
      return this.$store.state.guessHero.games || null;
    },
    // 当前游戏索引
    currentGame() {
      return this.$store.state.guessHero.currentGame;
    }
  },
  onLoad() {
    this.init();
    // 监听倒计时开始
    uni.$on("game_timeing", this.startTimer);
  },
  onShow() {
    console.log("%c [game.index] %c onShow 连接socket", "color:yellow", "color:#000");
    // 防止断线
    getApp().globalData.socket.initSocket();
  },
  onHide() {
    console.log("%c [game.index] %c onHide 页面隐藏", "color:yellow", "color:#000");
  },
  // tabbar页面
  // 执行:reLaunch,redirect
  // 不执行:navigate,navigateBack(退出应用),switchTab
  onUnload() {
    console.log("%c [game.index] %c onUnload 页面卸载", "color:yellow", "color:#000");
    // 清除计时器
    clearInterval(timer);
    uni.$off("game_timeing", this.startTimer);
  },
  methods: {
    // 初始化
    init() {
      // 该接口需要登录
      this.$store.dispatch("guessHero/getSunShine").then(() => {
        let p1 = this.$store.dispatch("setting/getConfig");
        let p2 = this.$store.dispatch("guessHero/getGames");
        let p3 = this.$store.dispatch("user/getUserInfo");
        return Promise.all([p1, p2, p3]).then(_ => {
          // 获取当前游戏的所有英雄
          this.$api.guessHero.getHeros(this.games[this.currentGame].game, 1, 9999).then(response => {
            this.$store.commit("guessHero/SET_CURRENT_GAME_HEROS", response.data.data.list || []);
          });
          // 保证登录成功再进入房间
          this.$store.dispatch("guessHero/enter", this.games[this.currentGame].game);
          return _;
        });
      });
    },
    // 游戏切换
    tabSelect(index) {
      this.$store.commit("guessHero/SET_CURRENT_GAME", index);
      // 消除当前选择项
      uni.$emit("betting_init");
      uni.setNavigationBarTitle({
        title: this.games[index].name + " - 英雄乐"
      });
    },
    // 监听当前改变
    onChangeBetting(e) {
      this.betting = e.betting;
      this.currentScore = e.spendScore;
      this.currentSun = e.spendSun;
    },
    // 开始计时
    startTimer(data) {
      this.time = data.time;
      // 开始计时前清空之前的倒计时
      clearInterval(timer);
      timer = setInterval(() => {
        this.time--;
        if (this.time < 1) {
          clearInterval(timer);
          this.time = 0;
          this.$store.commit("guessHero/SET_TYPE", "lotterying");
        }
      }, 1000);
    },

    // 提交预测,每场只允许提交一次
    onClickGuess: debounce(function() {
      // 判断是否已经提交
      if (this.games[this.currentGame].isSubmit) {
        uniApp.toast("每场只允许预测一次哦");
        return Promise.reject(false);
      }
      if (!this.betting.num.value && !this.betting.sex.value && !this.betting.remote.value && !this.betting.magic.value) {
        uniApp.toast("请至少预测一项");
        return Promise.reject(false);
      }
      return this.$store
        .dispatch("guessHero/postGuessHero", {
          game: this.games[this.currentGame].game,
          num: this.betting.num.value,
          num_ap: this.betting.num.double,
          sex: this.betting.sex.value,
          sex_ap: this.betting.sex.double,
          remote: this.betting.remote.value,
          remote_ap: this.betting.remote.double,
          magic: this.betting.magic.value,
          magic_ap: this.betting.magic.double
        })
        .then(_ => {
          // 更新阳光值
          this.$store.commit("guessHero/SET_SUN_SHINE", _.data.data);
          uniApp.toast("竞猜成功");
        })
        .catch(e => {
          uniApp.alert(e.message || e.data.msg);
        });
    })
  }
};
</script>

<style lang="scss">
.navBar {
  /* #ifndef APP-PLUS-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.navigator {
  width: 160rpx;
  color: yellow;
  text-decoration: underline;
}
// .scrollView,
// .gameNav {
//   width: 650rpx;
// }
.gameNav {
  height: 90rpx;
  /* #ifndef APP-PLUS-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  align-items: center;
}
.gameNavItem {
  margin: 0 20rpx;
}
.gameNavItemActive {
  border-bottom: 5rpx solid #ffffff;
  transform: scale(1.2);
}
.gameNavItemText {
  color: #ffffff;
  font-size: 28rpx;
}

.game.theme-2d {
  overflow: hidden;
  height: 100%;
  width: 100%;
  position: relative;
  background-color: #ffffff;
  // header 430rpx
  .header {
    width: 100%;
    height: 430rpx;
    position: relative;
    background-size: 100% 100%;
    overflow: hidden;
    .timeing {
      .menu {
        height: 140rpx;
        position: absolute;
        top: 160rpx;
        left: 0;
        display: flex;
        justify-content: space-between;
        flex-flow: column;
      }
      .logo {
        position: absolute;
        top: 20rpx;
        left: 0;
        right: 0;
        margin: 0 auto;
        width: 297rpx;
        height: 189rpx;
        image {
          width: 100%;
          height: 100%;
        }
      }
      .countText {
        position: absolute;
        top: 160rpx;
        left: 200rpx;
        text-shadow: 0 0 6rpx #fb7299, 0 0 10rpx #fb7299, 0 0 20rpx #fb7299, 0 0 30rpx #fb7299;
        color: #ffffff;
        .text {
          font-size: 32rpx;
        }
        .number {
          padding-left: 100rpx;
          font-size: 70rpx;
          text-align: right;
        }
      }
      .timer {
        position: absolute;
        bottom: 60rpx;
        left: 0;
        right: 0;
        width: 100%;
        text-align: center;
        text {
          font-size: 32rpx;
          display: inline-block;
          padding: 0 20rpx;
          text-shadow: 0 0 6rpx #fb7299, 0 0 10rpx #fb7299, 0 0 20rpx #fb7299, 0 0 30rpx #fb7299;
          color: #ffffff;
          &.animation {
            animation: timer 1s infinite;
          }
        }
      }
      .historyResultBox {
        position: absolute;
        right: 0;
        bottom: 50rpx;
        min-width: 180rpx;
      }
    }
    .waiting {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
      width: 100%;
    }
  }

  // 投注选项
  scroll-view.betting {
    height: calc(100% - 90rpx - 430rpx - 60rpx - 110rpx - 30rpx);
  }

  // 底部80rpx
  .settlement {
    background-color: #fbfafa;
    position: absolute;
    bottom: 30rpx;
    left: 0;
    right: 0;
    width: 100%;
    &-timeing {
      // 操作
      .operation {
        height: 80rpx;
        /* #ifndef APP-PLUS-NVUE */
        display: flex;
        /* #endif */
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        .btn {
          height: 100%;
          line-height: 80rpx;
          width: 210rpx;
          text-align: center;
          &.active {
            background-color: #fb7299;
            color: #ffffff;
            &:active {
              transform: scale(1.1);
            }
          }
          &.disabled {
            background: #cdd1d5;
          }
        }
      }
    }
    &-waiting {
      height: 80rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.operationLeft{
  padding-left: 20rpx;
}
.expectGetScore,.consumeSun{
  /* #ifndef APP-PLUS-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  align-items: center;
  line-height: 40rpx;
  font-size: 24rpx;
}
.expectGetScoreLabel,.econsumeSunLabel{
  
}
.expectGetScoreText,.consumeSunText{
  color: #fb7299;
}
// 我的积分 30rpx
.myScore{
  /* #ifndef APP-PLUS-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  font-size: 26rpx;
  height: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10rpx 0;
}
.myScoreLabel{
  font-size: 24rpx;
},
.myScoreText{
  font-size: 28rpx;
  color: #fb7299;
}






//  倒计时数字动画
@keyframes timer {
  0% {
    opacity: 0;
    transform: scale(1.2);
  }
  60% {
    opacity: 1;
    transform: scale(2);
  }
  100% {
    transform: scale(2.5);
    opacity: 0;
  }
}
</style>
